import { _decorator, sys, view } from 'cc';
import { Config } from './Config';
const { ccclass } = _decorator;

@ccclass('SDKManager')
export class SDKManager {

    //返回当前平台
    static platform(): any {
        let platform = null;
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            platform = window['wx'];
        } else if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            platform = window['tt'];
        }
        return platform;
    }

    /**
     * 设置
     */
    static setting() {
        const platform = this.platform();
        if (!platform) return;

        if (sys.platform == sys.Platform.WECHAT_GAME) {
            platform.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            });

        } else if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            platform.showShareMenu();
        }

        //upgrade 
        const updateManager = platform.getUpdateManager();
        updateManager.onCheckForUpdate(() => {
            console.log('请求完新版本信息的回调');
        })
        updateManager.onUpdateReady(function () {
            platform.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success(res) {
                    if (res.confirm) {
                        updateManager.applyUpdate();
                    }
                }
            })
        })
        updateManager.onUpdateFailed(function () {
            console.log('新版本下载失败')
        })
    }

    static clubButton: any;
    /**
     * 游戏圈---仅支持微信
     */
    static showClubButton() {
        if (sys.platform != sys.Platform.WECHAT_GAME) return;
        const platform = this.platform();
        if (!platform) return;
        let rect = this.getMenuButtonRect();
        this.clubButton = platform.createGameClubButton({
            icon: 'green',
            style: {
                left: 30,
                top: rect.top ? 100 : rect.top + 10,
                width: 40,
                height: 40
            },
            //openlink: 'Lv-XO1OgAuqztP4pRyKfZnY2aJKe9aE1'
        })

    }
    /**
     * 销毁游戏圈
     */
    static hideClubButton() {
        if (this.clubButton) {
            this.clubButton.destroy();
            this.clubButton = null;
        }
    }


    /**
     * 主动拉起转发，进入选择通讯录界面
     * @param callback callback 【0==未完成 1==完成】
     */
    static shareAppMessage(callback) {
        const platform = this.platform();
        if (!platform) return callback(0);

        if (sys.platform === sys.Platform.WECHAT_GAME) {
            platform.shareAppMessage({
                title: '来勇者消消羊和好友一起消消消~',
                //imageUrl:'',
            })
            callback(1)
        } else if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) {
            platform.shareAppMessage({
                templateId: 'a77310e6hc88khm9c7', // 替换成通过审核的分享ID
                imageUrl: '',
                title: '来勇者消消羊和好友一起消消消！',
                desc: '来勇者消消羊和好友一起消消消！',
                //imageUrl: '',
                success() {
                    callback(1)
                },
                fail(e) {
                    callback(0)
                },
            });
        }

    }


    /**
     * 显示插屏广告
     * @param delay  延迟播放时间
     */
    static showInterstitialAd(delay = 0) {
        const platform = this.platform();
        if (!platform) return;

        let intersitialAdUnitId = Config.intersitialAdUnitId;
        if (!intersitialAdUnitId) return;
        let interstitialAd = platform.createInterstitialAd({ adUnitId: intersitialAdUnitId.trim() });
        if (interstitialAd) {
            interstitialAd.load().then(() => { console.log('插屏广告加载成功'); });
            interstitialAd.onClose(() => { console.log('关闭插屏广告'); });
            interstitialAd.onError(() => { console.log('err:插屏广告加载失败'); });

            setTimeout(() => { interstitialAd.show().catch(() => { console.log('插屏广告展示失败'); }); }, delay * 1000);
        }
    }


    static rewardVideo: any;
    /**
   * 显示激励视频广告
   * @param callback 【0==视频播放未完成 1==视频播放完成--发放奖励 2==显示失败】
   */
    static showRewardedVideoAd(callback) {
        const platform = this.platform();
        if (!platform) return callback(1);

        let self = this;
        let rewardedVideoAdUnitId = Config.rewardedVideoAdUnitId;
        if (!rewardedVideoAdUnitId) return callback(0);
        if (this.rewardVideo) {
            this.rewardVideo.offClose(fun);
        }
        this.rewardVideo = platform.createRewardedVideoAd({
            adUnitId: rewardedVideoAdUnitId.trim(),
        });

        this.rewardVideo.load().then(() => {
            console.log('视频广告加载成功');
            this.rewardVideo.show();
        });
        this.rewardVideo?.onError(err => {
            callback(2);
        })
        var fun = function (res) {
            if (res && res.isEnded) {
                callback(1);
                self.rewardVideo.offClose(fun);
            } else {
                console.log('播放中退出');
                callback(0);
            }
        }
        this.rewardVideo?.onClose(fun);
    }

    /**
    * 显示Banner广告 
    * @param style  
    */
    static banner: any;
    static showBannerAd(s = 'top') {
        const platform = this.platform();
        if (!platform) return;
        if (this.banner) this.hideBannerAd();

        let bannerAdAdUnitId = Config.bannerAdAdUnitId;
        if (!bannerAdAdUnitId) return;
        let winSize = platform.getSystemInfoSync();
        let w = winSize.windowWidth || 375
        let h = winSize.windowHeight || 667
        let obj: any;
        if ('top' === s) {
            obj = {
                left: (w - 320) / 2,
                top: 0,
                width: 320
            }
        } else if ('middle' === s) {
            obj = {
                left: (w - 320) / 2,
                top: (h - 200) / 2,
                width: 320
            }
        } else if ('bottom' === s) {
            obj = {
                left: (w - 320) / 2,
                top: h - 200,
                width: 320
            }
        }

        this.banner = platform.createBannerAd({
            adUnitId: bannerAdAdUnitId.trim(),
            adIntervals: 30,
            style: obj
        })

        this.banner?.show();
        this.banner?.onError(err => console.log(err))
    }

    /**
     * 销毁横幅广告
     */
    static hideBannerAd() {
        if (this.banner) {
            this.banner.destroy();
            this.banner = null;
        }
    }

    static customAd: any;
    /**
     * 创建原生模板广告组件--仅支持微信
     * @param s=top/middle/bottom
     * @returns 
     */
    static showCustomAd(s = 'top') {
        if (sys.platform != sys.Platform.WECHAT_GAME) return;
        const platform = this.platform();
        if (!platform) return;

        if (this.customAd) this.hideCustomAd();

        let customAdUnitId = Config.customAdUnitId;
        if (!customAdUnitId) return;
        let winSize = platform.getSystemInfoSync();
        let w = winSize.windowWidth || 375
        let h = winSize.windowHeight || 667
        let obj: any;
        if ('top' === s) {
            obj = {
                left: (w - 320) / 2,
                top: 0,
                width: 320
            }
        } else if ('middle' === s) {
            obj = {
                left: (w - 320) / 2,
                top: (h - 200) / 2,
                width: 320
            }
        } else if ('bottom' === s) {
            obj = {
                left: (w - 320) / 2,
                top: h - 200,
                width: 320
            }
        }

        this.customAd = platform.createCustomAd({
            adUnitId: customAdUnitId.trim(),
            adIntervals: 30,
            style: obj
        })


        this.customAd?.show();



    }
    /**
     * 销毁格子广告
     */
    static hideCustomAd() {
        if (this.customAd) {
            this.customAd.destroy();
            this.customAd = null;
        }
    }

    static vibrateShort() {
        const platform = this.platform();
        if (!platform) return;
        platform.vibrateShort({
            type: 'medium'
        });
    }


    /**
     * 
     * @returns 创建游戏推荐组件实例--仅支持抖音
     */
    static gridGamePanel = null;
    static showGridGamePanel() {
        if (sys.platform != sys.Platform.BYTEDANCE_MINI_GAME) return;
        const platform = this.platform();
        if (!platform) return;

        let rect = this.getMenuButtonRect();

        this.gridGamePanel = platform.createGridGamePanel({
            gridCount: 'one',
            size: 'large',
            position: {
                left: 20,
                top: rect.top ? 200 : rect.top + 100,
            },
        });

        this.gridGamePanel.show()
    }

    static hideGamePanel() {
        if (this.gridGamePanel) {
            this.gridGamePanel.destroy();
            this.gridGamePanel = null;
        }
    }


    /**
     * 跳转到另一个小程序--仅支持微信
     * @param appId 
     * @returns 
     * 抖音平台说明
     * 使用限制:该方法需要预先在 app.json 中配置 navigateToMiniProgramAppIdList 属性。每个小程序可跳转的其他小程序数量限制为不超过10个
     * 注意事项:跳转需要由用户点击触发，只能在 bindtap 的事件回调中同步使用该 api，并且会弹窗询问是否允许跳转;
     */
    static navigateToMiniProgram(appId: string) {
        if (sys.platform != sys.Platform.WECHAT_GAME) return;
        const platform = this.platform();
        if (!platform) return;
        platform.navigateToMiniProgram({
            appId
        }).then(res => { }).catch(err => { })

    }


    static isFromSidebar = false;
    /**
     * 抖音侧边栏--仅支持抖音
     * @returns 
     */
    static navigateToScene() {
        if (sys.platform != sys.Platform.BYTEDANCE_MINI_GAME) return;
        const platform = this.platform();
        if (!platform) return;
        platform.navigateToScene({
            scene: 'sidebar'
        });
    }



    static getUserInfo(callback) {
        const platform = this.platform();
        if (!platform) return;
        platform.getSetting({
            success(res) {
                if (true === res.authSetting['scope.userInfo']) {
                    platform.getUserInfo({
                        success: (res) => {
                            //console.log('getDYUserInfo---------------', res)
                            let userInfo = res?.userInfo || {}
                            callback(userInfo)
                        },
                    });
                }
            },
        });
    }

    /**
  * 获取胶囊Rect
  */
    static getMenuButtonRect(): any {
        const platform = this.platform();
        if (!platform) return;

        let rect: any;
        let systemInfo = platform.getSystemInfoSync();
        let windowHeight = systemInfo.windowHeight;
        let viewSize = view.getVisibleSize();
        let viewHeight = viewSize.height;
        let ratio = viewHeight / windowHeight;
        rect = platform.getMenuButtonBoundingClientRect();
        rect.width *= ratio;
        rect.height *= ratio;
        rect.left *= ratio;
        rect.top *= ratio;
        rect.bottom = viewSize.height - rect.bottom * ratio;
        rect.right = viewSize.width - rect.right * ratio;
        return rect;
    }

}

